package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.common.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.req.AttrReqVo;
import com.atguigu.gulimall.product.vo.resp.AttrRespVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 思路：在原先的基础上添加了所属分类名称、所属分组的显示(eg:手机)
     * 注意：这里以下2个目标查询不使用sql的join查询，采用分批数据查询处理的方式，目的是：当数据量大时，使用join关联非常耗性能
     * 1、所属分类名称：根据catelog_id获取所属分类名称
     * 2、所属分组：用attr_id去pms_attr_attrgroup_relation表中查询对应的分组（默认设计属性和分组是1：1关系），eg:主体、屏幕
     */
    @Override
    public PageUtils queryAttrTypePage(Map<String, Object> params, String attrType, Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equals(attrType) ? ProductConstant.ATTR_TYPE_BASE.getCode() : ProductConstant.ATTR_TYPE_SALE.getCode());

        if (0L != catelogId) {
            // 查询全部
            queryWrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(obj ->
                    obj.eq("attr_id", key).or().like("attr_name", key));
        }
        // 查询相关AttrEntity实体数据
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> attrRespVos = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            // 1、所属分类名称：根据catelog_id获取所属分类名称(eg:手机)
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (ObjectUtils.isNotEmpty(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            // 2、所属分组：用attr_id去pms_attr_attrgroup_relation表中查询对应的分组（默认设计属性和分组是1：1关系），eg:主体、屏幕
            if ("base".equalsIgnoreCase(attrType)) {
                // 销售属性没有分组
                AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().lambda().eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
                if (ObjectUtils.isEmpty(relationEntity)) {
                    return attrRespVo;
                }
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (ObjectUtils.isNotEmpty(attrGroupEntity)) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 获取3级菜单所属分类完整路径
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);

        // 获取所属分组名称
        if (attrEntity.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().lambda()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            if (ObjectUtils.isEmpty(relationEntity)) {
                return attrRespVo;
            }
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
            if (ObjectUtils.isNotEmpty(groupEntity)) {
                attrRespVo.setGroupName(groupEntity.getAttrGroupName());
            }
        }
        return attrRespVo;
    }

    @Override
    public void saveAttr(AttrReqVo attrReqVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrReqVo, attrEntity);
        // 1、先insert原先的属性
        this.save(attrEntity);
        // 2、再insert关系表
        if (ProductConstant.ATTR_TYPE_BASE.getCode() == attrReqVo.getAttrType() && ObjectUtils.isNotEmpty(attrReqVo.getAttrGroupId())) {
            AttrAttrgroupRelationEntity relationEntity = AttrAttrgroupRelationEntity.builder()
                    .attrId(attrEntity.getAttrId())
                    .attrGroupId(attrReqVo.getAttrGroupId())
                    .build();
            relationService.save(relationEntity);
        }
    }

    @Override
    public void updateAttr(AttrReqVo attrReqVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrReqVo, attrEntity);
        // 1、先更新原先的实体
        this.updateById(attrEntity);

        // 2、再更新关系表
        if (ProductConstant.ATTR_TYPE_BASE.getCode() == attrReqVo.getAttrType()) {
            AttrAttrgroupRelationEntity relationEntity = AttrAttrgroupRelationEntity.builder()
                    .attrId(attrEntity.getAttrId())
                    .attrGroupId(attrReqVo.getAttrGroupId())
                    .build();
            int count = relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().lambda()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrReqVo.getAttrId()));
            if (count > 0) {
                relationService.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().lambda().eq(AttrAttrgroupRelationEntity::getAttrId, attrReqVo.getAttrId()));
            } else {
                relationService.save(relationEntity);
            }
        }
    }

    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        // 前提：当前分组只能关联自己所属的分类（手机分类）里面的所有属性
        // 1、根据attrgroupId在pms_attr_group获取catelog_id
        AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = groupEntity.getCatelogId();

        // 2、当前分组只能关联别的分组没有引用的属性，根据catelog_id在pms_attr_group查询所有该分类下的分组
        List<AttrGroupEntity> groupEntityList = attrGroupService.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, catelogId));
        List<Long> groupIds = groupEntityList.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());

        // 3、将获取到的所有分组id在pms_attr_attrgroup_relation查询到所有关联的attrIds
        List<AttrAttrgroupRelationEntity> relationEntityList = relationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
        List<Long> attrIds = relationEntityList.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        // 4、然后通过catelog_id（分类id）在pms_attr查询所有“atty_type = base”的数据，最后将第3步获取到的attrIds排除
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.ATTR_TYPE_BASE.getCode())
                .notIn("attr_id", attrIds);

        // 5、执行上述的查询QuerryWrapper得到结果，再筛选出param.key的数据，最后返回分页数据
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(obj -> obj.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }
}